<?php
namespace app\index\controller;

use think\Controller;

class Index extends Controller
{
    public function index()
    {
        $data = db('daan')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function daan() {
        $id = input('param.id');
        $data = db('daan')->where('id', $id)->find();
        $this->assign('data', $data);
        return view();
    }

    public function admin() {

        if (session('username') != 'admin' || session('password') != '12345666') {
            return $this->fetch('login');
        }
        $data = db('daan')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function save_daan() {
        if (session('username') != 'admin' || session('password') != '12345666') {
            return $this->fetch('login');
        }

        $id = input('param.id');

        if (request()->isPost()) {
            $name = input('param.name');
            $content = input('param.content');

            if ($id) {
                $rs = db('daan')->where('id', $id)->update(['name' => $name, 'content' => $content]);
            } else {
                $rs = db('daan')->insert(['name' => $name, 'content' => $content]);
            }
            if ($rs) {
                $this->success('保存成功');
            } else {
                $this->success('保存失败');
            }
        } else {
            $data = [];
            if ($id) {
                $data = db('daan')->where('id', $id)->find();
            }

            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    public function login() {
        $username = input('param.username');
        $password = input('param.password');
        if ($username == 'admin' && $password == '12345666') {
            session('username', 'admin');
            session('password', '12345666');
            $this->success('登录成功', url('admin'));
        } else {
            $this->error('登录失败');
        }
    }
}
